package org.xaviera.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class StandardJavaSerializationFactory implements SerializationFactory<Object> {

	@Override
	public Serializer<Object> createSerializerForType(Class<Object> type, OutputStream out) throws IOException {
		return new StandardJavaSerializer(out);
	}

	@Override
	public Deserializer<Object> createDeserializerForType(Class<Object> type, InputStream in) throws IOException {
		return new StandardJavaDeserializer(in);
	}
	

	public class StandardJavaSerializer implements Serializer<Object> {
		
		private ObjectOutputStream out;
		
		public StandardJavaSerializer(OutputStream out) throws IOException {
			if (out instanceof ObjectOutputStream) {
				this.out = (ObjectOutputStream) out;
			}
			else {
				this.out = new ObjectOutputStream(out);
			}
		}
		
		@Override
		public void write(Object value) throws IOException {
			out.writeObject(value);
		}
		
	};
	
	
	public class StandardJavaDeserializer implements Deserializer<Object> {
		
		private ObjectInputStream in;
		
		public StandardJavaDeserializer(InputStream in) throws IOException {
			if (in instanceof ObjectInputStream) {
				this.in = (ObjectInputStream) in;
			}
			else {
				this.in = new ObjectInputStream(in);
			}
		}

		@Override
		public Object read() throws IOException, ClassNotFoundException {
			return in.readObject();
		}
		
	};
	
}
